package cn.iocoder.yudao.module.engine.service.core.messagestore.impl;

import cn.iocoder.yudao.module.engine.anno.Syn;
import cn.iocoder.yudao.module.engine.model.context.AIMessageContext;
import cn.iocoder.yudao.module.engine.model.context.ControlEngineContext;
import cn.iocoder.yudao.module.engine.model.context.EngineSessionContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineOutputData;
import cn.iocoder.yudao.module.engine.service.core.messagestore.AbstractMessageStore;
import cn.iocoder.yudao.module.engine.service.core.messagestore.MessageStoreManager;
import cn.iocoder.yudao.module.infra.llm.model.LLMMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

@Slf4j
@Syn
@Order(101)
@Service("messageStore-historyQueue")
public class HistoryQueueMessageStore extends AbstractMessageStore {
    @Resource
    private MessageStoreManager messageStoreManager;

    @PostConstruct
    public void init() {
        messageStoreManager.registerStore("messageStore-historyQueue", this);
    }

    @Override
    public void executeSaveMessages(ControlEngineContext engineContext,
                                    @Nullable AIMessageContext messageCtx,
                                    EngineOutputData.Audio audio) {
        final EngineSessionContext sessionContext = engineContext.getSessionCtx();

        final String messageId = audio.getChatId();
        sessionContext.getHistoryMessageQueue().add(
                LLMMessage.builder()
                        .messageId(messageId)
                        .userText(audio.getFromMessage())
                        .replyText(getReplyText(messageCtx, audio))
                        .build());
        log.info("添加消息到历史队列, messageId = {}, queueSize = {}",
                messageId, sessionContext.getHistoryMessageQueue().size());
    }

}
